// 通用工具函数库

// Toast通知系统
function showToast(message, type = 'success') {
  // 确保toast容器存在
  let toastContainer = document.getElementById('toast-container');
  if (!toastContainer) {
    toastContainer = document.createElement('div');
    toastContainer.id = 'toast-container';
    toastContainer.className = 'fixed top-4 right-4 z-50 flex flex-col gap-2';
    document.body.appendChild(toastContainer);
  }

  // 创建toast元素
  const toast = document.createElement('div');
  toast.className = `px-4 py-3 rounded-lg shadow-lg transform transition-all duration-300 ease-in-out translate-x-full opacity-0 ${type === 'success' ? 'bg-green-100 text-green-800 border border-green-200' : type === 'error' ? 'bg-red-100 text-red-800 border border-red-200' : 'bg-blue-100 text-blue-800 border border-blue-200'}`;
  toast.textContent = message;

  // 添加到容器
  toastContainer.appendChild(toast);

  // 显示动画
  setTimeout(() => {
    toast.classList.remove('translate-x-full', 'opacity-0');
    toast.classList.add('translate-x-0', 'opacity-100');
  }, 10);

  // 自动隐藏
  setTimeout(() => {
    toast.classList.add('translate-x-full', 'opacity-0');
    setTimeout(() => {
      if (toast.parentNode) {
        toast.parentNode.removeChild(toast);
      }
    }, 300);
  }, 3000);
}

// 数字动画函数
function animateNumber(element, target, duration = 1000) {
  const start = 0;
  const increment = target / (duration / 16);
  let current = start;

  const timer = setInterval(() => {
    current += increment;
    if (current >= target) {
      current = target;
      clearInterval(timer);
    }
    element.textContent = Math.floor(current).toLocaleString();
  }, 16);
}

// 加载状态管理
function showLoading(element) {
  if (!element) return;
  
  // 如果是body元素，创建覆盖整个页面的遮罩
  if (element === document.body) {
    // 检查是否已经存在加载遮罩
    let loadingOverlay = document.getElementById('loadingOverlay');
    if (!loadingOverlay) {
      loadingOverlay = document.createElement('div');
      loadingOverlay.id = 'loadingOverlay';
      loadingOverlay.className = 'fixed inset-0 bg-white bg-opacity-80 flex items-center justify-center z-50';
      loadingOverlay.innerHTML = '<div class="text-center"><div class="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500 mb-3"></div><p class="text-gray-700">加载中...</p></div>';
      document.body.appendChild(loadingOverlay);
    }
    loadingOverlay.classList.remove('hidden');
  } else {
    // 对于普通元素，保留原有的实现
    element.setAttribute('disabled', 'disabled');
    element.setAttribute('data-original-content', element.innerHTML);
    element.innerHTML = '<span class="inline-block animate-spin rounded-full h-4 w-4 border-b-2 border-current"></span> 加载中...';
  }
}

function hideLoading(element, originalText) {
  if (!element) return;
  
  // 如果是body元素，移除遮罩
  if (element === document.body) {
    const loadingOverlay = document.getElementById('loadingOverlay');
    if (loadingOverlay) {
      loadingOverlay.classList.add('hidden');
    }
  } else {
    // 对于普通元素，恢复原始内容
    element.removeAttribute('disabled');
    const originalContent = element.getAttribute('data-original-content');
    if (originalContent) {
      element.innerHTML = originalContent;
      element.removeAttribute('data-original-content');
    } else if (originalText) {
      element.textContent = originalText;
    }
  }
}

// 表单验证
function validateForm(form) {
  const inputs = form.querySelectorAll('input[required], select[required], textarea[required]');
  let isValid = true;

  inputs.forEach(input => {
    if (!input.value.trim()) {
      isValid = false;
      input.classList.add('border-red-300', 'focus:ring-red-500', 'focus:border-red-500');
      input.setAttribute('aria-invalid', 'true');
    } else {
      input.classList.remove('border-red-300', 'focus:ring-red-500', 'focus:border-red-500');
      input.setAttribute('aria-invalid', 'false');
    }
  });

  return isValid;
}

// 密码强度检测
function checkPasswordStrength(password) {
  let strength = 0;
  let feedback = '';

  if (password.length >= 8) strength++;
  if (password.match(/[a-z]/)) strength++;
  if (password.match(/[A-Z]/)) strength++;
  if (password.match(/[0-9]/)) strength++;
  if (password.match(/[^a-zA-Z0-9]/)) strength++;

  if (strength <= 2) {
    feedback = '弱';
  } else if (strength <= 4) {
    feedback = '中';
  } else {
    feedback = '强';
  }

  return { strength, feedback };
}

// 生成唯一ID
function generateId(prefix = '') {
  return prefix + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
}

// 格式化日期
function formatDate(dateString) {
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
}

// 复制到剪贴板
async function copyToClipboard(text) {
  try {
    await navigator.clipboard.writeText(text);
    showToast('已复制到剪贴板', 'success');
    return true;
  } catch (err) {
    console.error('复制失败:', err);
    showToast('复制失败，请手动复制', 'error');
    return false;
  }
}

// 模态框控制
function openModal(modalId) {
  const modal = document.getElementById(modalId);
  if (modal) {
    modal.classList.remove('hidden');
    document.body.classList.add('overflow-hidden');
  }
}

function closeModal(modalId) {
  const modal = document.getElementById(modalId);
  if (modal) {
    modal.classList.add('hidden');
    document.body.classList.remove('overflow-hidden');
  }
}

// 添加模态框关闭事件
function addModalCloseEvents(modalId) {
  const modal = document.getElementById(modalId);
  if (!modal) return;

  // 点击模态框外部关闭
  modal.addEventListener('click', (e) => {
    if (e.target === modal) {
      closeModal(modalId);
    }
  });

  // ESC键关闭
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
      closeModal(modalId);
    }
  });
}

// 初始化所有模态框
function initModals() {
  const modals = document.querySelectorAll('[id$="-modal"]');
  modals.forEach(modal => {
    addModalCloseEvents(modal.id);
  });
}

// 隐藏所有toast通知
function hideToast() {
  const toastContainer = document.getElementById('toast-container');
  if (toastContainer) {
    // 获取所有toast元素
    const toasts = toastContainer.querySelectorAll('div');
    toasts.forEach(toast => {
      // 添加隐藏动画
      toast.classList.add('translate-x-full', 'opacity-0');
      // 动画结束后移除元素
      setTimeout(() => {
        if (toast.parentNode) {
          toast.parentNode.removeChild(toast);
        }
      }, 300);
    });
  }
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', () => {
  // 将常用函数挂载到window对象，使其成为全局函数
  window.showToast = showToast;
  window.hideToast = hideToast;
  window.animateNumber = animateNumber;
  window.showLoading = showLoading;
  window.hideLoading = hideLoading;
  window.validateForm = validateForm;
  window.checkPasswordStrength = checkPasswordStrength;
  window.generateId = generateId;
  window.formatDate = formatDate;
  window.copyToClipboard = copyToClipboard;
  window.openModal = openModal;
  window.closeModal = closeModal;
  window.addModalCloseEvents = addModalCloseEvents;
  window.initModals = initModals;
  // 初始化模态框
  initModals();

  // 添加通用的工具类样式
  const style = document.createElement('style');
  style.textContent = `
    /* 状态徽章样式 */
    .status-badge {
      display: inline-flex;
      align-items: center;
      padding: 0.25rem 0.75rem;
      border-radius: 9999px;
      font-size: 0.75rem;
      font-weight: 500;
    }

    .status-pending {
      background-color: #fef3c7;
      color: #92400e;
      border: 1px solid #fde68a;
    }

    .status-approved {
      background-color: #d1fae5;
      color: #065f46;
      border: 1px solid #a7f3d0;
    }

    .status-rejected {
      background-color: #fee2e2;
      color: #991b1b;
      border: 1px solid #fecaca;
    }

    .status-active {
      background-color: #dbeafe;
      color: #1e40af;
      border: 1px solid #bfdbfe;
    }

    .status-inactive {
      background-color: #f3f4f6;
      color: #4b5563;
      border: 1px solid #e5e7eb;
    }

    /* 统计卡片样式 */
    .stat-card {
      @apply bg-white/90 backdrop-blur-sm border border-gray-200 rounded-xl shadow-sm hover:shadow-md transition-all duration-300;
    }

    /* 按钮加载状态 */
    .btn-loading {
      opacity: 0.7;
      cursor: not-allowed;
    }

    /* 空数据提示 */
    .empty-state {
      @apply text-center py-12 px-4 bg-gray-50 rounded-lg border border-dashed border-gray-200;
    }

    /* 渐入动画 */
    @keyframes fadeInUp {
      from {
        opacity: 0;
        transform: translateY(20px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }

    .animate-fadeInUp {
      animation: fadeInUp 0.5s ease-out forwards;
    }

    /* 脉冲动画 */
    @keyframes pulse {
      0%, 100% {
        opacity: 1;
      }
      50% {
        opacity: 0.5;
      }
    }

    .animate-pulse {
      animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
    }

    /* 图标缩放动画 */
    @keyframes scaleIn {
      from {
        transform: scale(0.8);
        opacity: 0;
      }
      to {
        transform: scale(1);
        opacity: 1;
      }
    }

    .animate-scaleIn {
      animation: scaleIn 0.3s ease-out forwards;
    }
  `;
  document.head.appendChild(style);
});